<template>
  <div v-if="visible" class="booking-modal-overlay" @click="handleOverlayClick">
    <div class="booking-modal" @click.stop>
      <!-- 弹窗头部 -->
      <div class="modal-header">
        <div class="header-left">
          <el-icon @click="handleClose" class="close-icon"><Close /></el-icon>
          <span class="modal-title">预约服务</span>
        </div>
      </div>
      
      <!-- 弹窗内容 -->
      <div class="modal-content">
        <!-- 服务信息展示 -->
        <div class="service-info-section">
          <div class="service-image">
            <img :src="selectedService.img" :alt="selectedService.title" />
          </div>
          <div class="service-details">
            <h4 class="service-title">{{ selectedService.title }}</h4>
            <p class="service-subtitle">{{ selectedService.subTitle }}</p>
            <div class="price-info">
              <span class="current-price">{{ selectedService.priceAfterDiscounts }}</span>
              <span class="original-price">{{ selectedService.originalPrice }}</span>
            </div>
          </div>
        </div>

        <!-- 预约时间选择 -->
        <div class="time-section">
          <h4 class="section-subtitle">选择预约时间</h4>
          <div class="time-picker">
            <el-date-picker
              v-model="appointmentDate"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              style="width: 100%; margin-bottom: 10px"
            />
            <el-time-picker
              v-model="appointmentTime"
              placeholder="选择时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </div>
        </div>

        <!-- 联系人信息 -->
        <div class="contact-section">
          <h4 class="section-subtitle">联系人信息</h4>
          <el-form ref="contactForm" :model="contactInfo" label-width="80px">
            <el-form-item label="姓名">
              <el-input v-model="contactInfo.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="contactInfo.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="contactInfo.address" placeholder="请输入服务地址" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input 
                v-model="contactInfo.remark" 
                type="textarea" 
                placeholder="请输入特殊要求或备注"
                :rows="3"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 价格明细 -->
        <div class="price-detail-section">
          <h4 class="section-subtitle">价格明细</h4>
          <div class="price-detail">
            <div class="price-row">
              <span>服务费用</span>
              <span class="price-value">{{ selectedService.priceAfterDiscounts }}</span>
            </div>
            <div class="price-row">
              <span>服务费</span>
              <span class="price-value">{{ serviceFee }}</span>
            </div>
            <div class="price-row total">
              <span>总计</span>
              <span class="price-value total-price">{{ calculateTotalPrice() }}</span>
            </div>
          </div>
        </div>

        <!-- 服务须知 -->
        <div class="notice-section">
          <h4 class="section-subtitle">服务须知</h4>
          <ul class="notice-list">
            <li>请确保填写的联系信息真实有效</li>
            <li>服务人员将在预约时间前30分钟联系您</li>
            <li>如需取消预约，请提前2小时联系客服</li>
            <li>服务完成后请确认服务质量</li>
            <li>如有问题请及时联系客服处理</li>
          </ul>
        </div>
      </div>

      <!-- 弹窗底部按钮 -->
      <div class="modal-footer">
        <el-button class="cancel-btn" @click="handleClose">取消</el-button>
        <el-button type="primary" class="submit-btn" @click="handleSubmit">确认预约</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import { createServiceBookingApi } from '@/api/service'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  selectedService: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close', 'submit'])

// 响应式数据
const appointmentDate = ref('')
const appointmentTime = ref('')
const contactForm = ref(null)

// 联系人信息
const contactInfo = reactive({
  name: '',
  phone: '',
  address: '',
  remark: ''
})

// 手机号验证正则
const PHONE_REG = /^1[3-9]\d{9}$/

// 禁用日期（今天之前的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 服务费计算
const serviceFee = computed(() => {
  if (!props.selectedService.priceAfterDiscounts) return '¥0'
  // 提取价格数字
  const price = parseFloat(props.selectedService.priceAfterDiscounts.replace(/[^\d.]/g, ''))
  return '¥' + Math.floor(price * 0.1)
})

// 计算总价
const calculateTotalPrice = () => {
  if (!props.selectedService.priceAfterDiscounts) return '¥0'
  
  const price = parseFloat(props.selectedService.priceAfterDiscounts.replace(/[^\d.]/g, ''))
  const serviceFeeNum = Math.floor(price * 0.1)
  
  return '¥' + (price + serviceFeeNum)
}

// 提交预约
const handleSubmit = async () => {
  // 表单验证
  if (!appointmentDate.value) {
    ElMessage.warning('请选择预约日期')
    return
  }
  if (!appointmentTime.value) {
    ElMessage.warning('请选择预约时间')
    return
  }
  
  if (!contactInfo.name) {
    ElMessage.warning('请输入联系人姓名')
    return
  }
  if (!contactInfo.phone) {
    ElMessage.warning('请输入手机号')
    return
  }
  if (!PHONE_REG.test(contactInfo.phone)) {
    ElMessage.warning('请输入合法的手机号')
    return
  }
  if (!contactInfo.address) {
    ElMessage.warning('请输入服务地址')
    return
  }
  
  // 构建预约数据 - 匹配后端API格式
  const bookingData = {
    serviceId: props.selectedService.id || 1, // 服务ID，需要从服务配置中获取
    contactName: contactInfo.name,
    contactPhone: contactInfo.phone,
    address: contactInfo.address,
    appointmentDate: appointmentDate.value,
    appointmentTime: appointmentTime.value,
    serviceDescription: props.selectedService.subTitle || props.selectedService.title,
    specialRequirements: contactInfo.remark,
    totalPrice: parseFloat(calculateTotalPrice().replace('¥', ''))
  }
  
    console.log('提交预约数据:', bookingData)
  
  try {
    // 显示加载状态
    ElMessage.info('正在提交预约，请稍候...')
    
    // 发送API请求到后端
    const response = await createServiceBookingApi(bookingData)
    
    console.log('预约响应:', response)
    console.log('响应码:', response?.code)
    console.log('响应消息:', response?.message)
    console.log('响应数据:', response?.data)
    
    // 处理不同的响应格式
    if (response && (response.code === 0 || response.code === 200)) {
      ElMessage.success('预约成功！服务人员将尽快联系您')
      // 发射提交事件，传递预约数据
      emit('submit', bookingData)
      // 重置表单
      resetForm()
      // 关闭弹窗
      emit('close')
    } else {
      console.error('预约失败，响应:', response)
      ElMessage.error(response?.message || '预约失败，请重试')
    }
  } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error(error.message || '预约失败，请检查网络连接')
  }
}

// 重置表单
const resetForm = () => {
  appointmentDate.value = ''
  appointmentTime.value = ''
  contactInfo.name = ''
  contactInfo.phone = ''
  contactInfo.address = ''
  contactInfo.remark = ''
}

// 关闭弹窗
const handleClose = () => {
  resetForm()
  emit('close')
}

// 点击遮罩层关闭
const handleOverlayClick = () => {
  handleClose()
}

// 监听弹窗显示状态，重置表单
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm()
  }
})
</script>

<style scoped>
.booking-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.booking-modal {
  background-color: #fff;
  border-radius: 16px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.close-icon {
  font-size: 20px;
  cursor: pointer;
  color: #666;
  transition: color 0.3s ease;
}

.close-icon:hover {
  color: #333;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.modal-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 服务信息样式 */
.service-info-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 12px;
}

.service-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.service-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.service-details {
  flex: 1;
}

.service-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.service-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px 0;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #e74c3c;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.section-subtitle {
  font-size: 16px;
  font-weight: 600;
  margin: 20px 0 12px;
  color: #333;
}

/* 时间选择样式 */
.time-picker {
  margin-bottom: 8px;
}

/* 联系人信息样式 */
.contact-section {
  margin-top: 20px;
}

/* 价格明细样式 */
.price-detail {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 8px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 14px;
}

.price-row.total {
  margin-top: 8px;
  padding-top: 12px;
  border-top: 1px solid #e0e0e0;
  font-weight: 600;
}

.price-value {
  color: #666;
}

.price-value.total-price {
  color: #e74c3c;
  font-size: 16px;
}

/* 服务须知样式 */
.notice-list {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
  padding-left: 16px;
}

.notice-list li {
  margin-bottom: 4px;
}

/* 弹窗底部按钮样式 */
.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.cancel-btn {
  flex: 1;
  height: 44px;
  font-size: 16px;
}

.submit-btn {
  flex: 1;
  height: 44px;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .booking-modal-overlay {
    padding: 10px;
  }
  
  .booking-modal {
    max-height: 95vh;
  }
  
  .modal-content {
    padding: 16px;
  }
  
  .service-info-section {
    flex-direction: column;
    gap: 12px;
  }
  
  .service-image {
    width: 100%;
    height: 120px;
  }
  
  .modal-footer {
    padding: 12px 16px;
  }
  
  .cancel-btn,
  .submit-btn {
    height: 40px;
    font-size: 14px;
  }
}
</style>
